package filepro;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author small瑞
 */
public class FileSplitter {

    private int size ;

    private  FileSplitter(){

    }

    public static FileSplitter getInstance( int size){
        FileSplitter fileSplitter = new FileSplitter();
        fileSplitter.size = size;
        return fileSplitter;
    }

    public int split(File origin , File destination) throws IOException {
        if(!destination.isDirectory()){
            throw new RuntimeException("目标不是一个文件夹!");
        }
        if(!origin.isFile()){
            throw new RuntimeException("源文件不是一个文件!");
        }
        String path = destination.getAbsolutePath();
        String type = origin.getName().substring(origin.getName().indexOf('.')+1);
        FileInputStream fileInputStream = new FileInputStream(origin);
        int available = fileInputStream.available();
        int i = 0 ;
        int count = available%this.size==0?available/this.size:available/this.size+1;
        byte[] bytes = new byte[count];
        while(i < count){
            File destination1 = new File(path+"/destination"+i+"."+type);
            if(!destination1.exists()){
                destination1.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(destination1);

            fileInputStream.read(bytes);
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            fileOutputStream.close();
            i++;
        }
        fileInputStream.close();
        return  count;
    }

    public static void main(String[] args) throws IOException{
        String path = "G:\\牵丝戏.txt";
        File origin = new File(path);
        File destination = new File("G:\\");
//        FileSplitter fileSplitter = FileSplitter.getInstance(12);
//        int split = fileSplitter.split(origin, destination);
        System.out.println(Arrays.toString(destination.list()));
    }
}
